package com.weiz.security;

import com.weiz.domain.SysPermission;
import com.weiz.domain.SysRole;
import com.weiz.domain.SysUser;
import com.weiz.repository.SysUserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyCustomUserService implements UserDetailsService{


    private final static Logger logger = LoggerFactory.getLogger(MyCustomUserService.class);

    @Autowired
    private SysUserRepository sysUserRepository;

    /**
     * 通过验证 将用的所有角色 用户信息中
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        logger.info("根据名称获取用户信息： username is {}",username);

        SysUser user = sysUserRepository.findUserByUsername(username);
        if(user == null)
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));

        List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
        // 添加角色
        List<SysRole> roles = sysUserRepository.findRolesByUsername(user.getUsername());
        for (SysRole role : roles) {
            if (null != role) {
                grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            }
        }

        //添加权限
        List<SysPermission> permissions = sysUserRepository.findPermissionsByUsername(user.getUsername());
        logger.info("权限个数为{}",permissions.size());
        for (SysPermission permission : permissions) {
            if (permission != null && permission.getName()!=null) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
                //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                grantedAuthorities.add(grantedAuthority);
            }
        }
        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}
